<template>
  <div class="dashboard-editor-container">
    <div class="flex flex-row flex-wrap top-box">
      <div class="card flex flex-row bg1" @click="getAllList">
        <div class="ico-box"><img src="@/assets/baqsj/ico1.png" alt=""> </div>
        <div class="label ml15 line-height-50 font19">事件总数</div>
        <div class="number">{{ dashboardValue.count.all }}</div>
      </div>
      <div class="card flex flex-row bg2" @click="getCompleteList">
        <div class="ico-box"><img src="@/assets/baqsj/ico2.png" alt=""></div>
        <div class="label ml15 line-height-50 font19">已完成</div>
        <div class="number">{{ dashboardValue.count.complete }}</div>
      </div>
      <div class="card flex flex-row bg3" @click="getProcessList">
        <div class="ico-box"><img src="@/assets/baqsj/ico3.png" alt=""></div>
        <div class="label ml15 line-height-50 font19">进行中</div>
        <div class="number">{{ dashboardValue.count.process }}</div>
      </div>
    </div>
    <el-card class="box-card">
      <el-form ref="listQuery" :model="listQuery" :inline="true">
        <el-form-item label="事件分类" prop="title">
          <el-select
            v-model="listQuery.title"
            placeholder="请选择事件分类"
            size="small"
            clearable
            filterable
            style="width: 200px"
            @change="getList"
          >
            <el-option v-for="(item, index) in classOpts" :key="index" :label="item.label" :value="item.val">
              <span style="float: left;margin-right:30px">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.category
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发生地点" prop="fsdd" label-width="90px">
          <el-select
            v-model="listQuery.fsdd"
            placeholder="请选择"
            size="small"
            clearable
            style="width: 130px"
            @change="getList"
          >
            <el-option label="病房" value="病房" />
            <el-option label="门诊" value="门诊" />
            <el-option label="急诊" value="急诊" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="事件名称" prop="title" label-width="90px" class="mr20">
          <el-input v-model="listQuery.title" placeholder="请输入事件名称" clearable size="small" style="width: 180px" @keyup.enter.native="getList" />
        </el-form-item> -->
        <el-form-item label="上报时间">
          <el-date-picker
            v-model="timeValue"
            clearable
            size="small"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            @change="getList"
          />
        </el-form-item>
        <el-form-item label="发生日期">
          <el-date-picker
            v-model="timeFsValue"
            clearable
            size="small"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            @change="getList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="getList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          <el-button v-permisaction="['baqsj:analyse:list:export']" type="primary" icon="el-icon-download" size="small" @click="handleExportList">导出全部</el-button>
          <el-button
            v-permisaction="['baqsj:analyse:list:exportYw']"
            type="primary"
            icon="el-icon-download"
            size="small"
            @click="handleYwExportList"
          >导出药物不良反应事件</el-button>
          <el-button
            v-permisaction="['baqsj:analyse:list:exportQx']"
            type="primary"
            icon="el-icon-download"
            size="small"
            @click="handleYLQXExportList"
          >导出医疗器械事件</el-button>
          <el-button type="primary" icon="el-icon-upload2" size="small" @click="handleADR">ADR上报</el-button>
          <el-button type="primary" icon="el-icon-notebook-2" size="small" @click="handleRjView">历史上报</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        border
        :data="ticketList"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="#" type="index" :index="indexAdd" width="80" align="center" />
        <el-table-column label="事件名称" prop="title" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="病区" prop="apply_dept" :show-overflow-tooltip="true" align="center" width="140" />
        <el-table-column label="审批状态" :show-overflow-tooltip="true" align="center" width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 2">
              已撤回上报
            </span>
            <span v-else>
              {{ scope.row.state_name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="当前审批人" :show-overflow-tooltip="true" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.principals }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上报人" :show-overflow-tooltip="true" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.createUsers }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上报时间" align="center" prop="create_time" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.create_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)">上报数据</el-button>
            <!-- <el-button v-if="scope.row.is_end === 0" size="mini" type="text" icon="el-icon-refresh-left" @click="recallOrder(scope.row)" :disabled="recallDisabled">撤回</el-button> -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-time"
              @click="handleHistoryView(scope.row)"
            >审批历史</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              class="del-btn"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="转交" :visible.sync="dialogVisible" width="30%">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="60px" class="demo-ruleForm">
          <el-form-item label="节点" prop="node_id">
            <el-select v-model="ruleForm.node_id" placeholder="选择节点" size="small" style="width: 100%">
              <el-option v-for="(item, index) in nodeList" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户" prop="user_id">
            <el-select v-model="ruleForm.user_id" filterable placeholder="选择用户" size="small" style="width: 100%">
              <el-option v-for="(item, index) in users" :key="index" :label="item.nickName" :value="item.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="ruleForm.remarks" type="textarea" size="small" />
          </el-form-item>
          <el-form-item style="text-align: right">
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageIndex"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <HistoryDialog ref="historyDialog" />
    <RjList ref="rjDialog" />
  </div>
</template>
<script>
import {
  workOrderList,
  unityWorkOrder,
  deleteWorkOrder,
  recallWorkOrder,
  inversionWorkOrder,
  recyclingWorkOrder
} from '@/api/baqsj/work-order'
import { Message, Loading } from 'element-ui'
import { listAllUser } from '@/api/system/sysuser'
import { processOpts } from '@/api/process/admin/process'
import HistoryDialog from '@/views/baqsj/components/history'
import RjList from './components/ruijing/index.vue'
import WorkOrderSearch from './components/search/index'
import ChartCard from './components/ChartCard'
import { initData, projectData } from '@/api/baqsj/analyse'
import { formatJson } from '@/utils'
import { handleYwExport, handleYLQXExport } from '@/utils/handleExcel'
export default {
  name: 'BaqsjAnalyse',
  components: {
    ChartCard,
    WorkOrderSearch,
    HistoryDialog,
    RjList
  },
  data() {
    return {
      classOpts: [],
      timeValue: '',
      timeFsValue: '',
      dashboardValue: {
        count: {}
      },
      userMap: {},
      excelLoading: false,
      loadingFull: null,
      recallDisabled: false,
      users: [],
      nodeList: [],
      nsVisible: false,
      dialogVisible: false,
      queryParams: {},
      total: 0,
      loading: false,
      ticketList: [],
      ywblfyList: [],
      ylqxList: [],
      currentNs: [],
      listQuery: {
        title: '',
        projectNo: '',
        projectClassify: '',
        leaderName: '',
        applyDepart: '',
        nodeName: '',
        page: 1,
        per_page: 10
      },
      ruleForm: {
        work_order_id: '',
        node_id: '',
        user_id: '',
        remarks: ''
      },
      rules: {
        node_id: [{ required: true, message: '请选择节点', trigger: 'change' }],
        user_id: [{ required: true, message: '请选择用户', trigger: 'change' }]
      },
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }
        ]
      }
    }
  },
  created() {
    this.getProcessOpts()
    this.initUsers()
  },
  methods: {
    async getProcessOpts() {
      const res = await processOpts({})
      this.classOpts = res.data
    },
    indexAdd(index) {
      const page = this.queryParams.pageIndex // 当前页码
      const pagesize = this.queryParams.pageSize // 每页条数
      return index + 1 + (page - 1) * pagesize
    },
    handleRjView() {
      this.$refs.rjDialog.open()
    },
    recallOrder(row) {
      this.$confirm('是否确认撤回该上报?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.recallDisabled = true
        const recallParams = {
          work_oroder_id: row.id,
          process_id: row.process
        }
        recallWorkOrder(recallParams)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '撤回成功!'
              })
              this.recallDisabled = false
              this.initUsers()
            }
          })
          .catch(() => {
            this.recallDisabled = false
          })
      })
    },
    async handleADR() {
      window.open('http://124.222.144.66:8087/', '_blank')
    },
    async handleYLQXExportList() {
      const _this = this
      this.excelLoading = true
      this.loadingFull = Loading.service({
        target: document.querySelector('.app-wrapper'),
        lock: true,
        text: '正在导出中，请稍后……',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'zIndex9999'
      })
      let startTime
      let endTime
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        startTime = ''
        endTime = ''
      } else {
        startTime = this.parseTime(this.timeValue[0])
        endTime = this.parseTime(this.timeValue[1])
      }
      const res = await workOrderList({
        page: 1,
        per_page: 99999,
        classify: 8,
        startTime,
        endTime
      })
      this.ylqxList = res.data.data || []
      let startDate
      let endDate
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        startDate = ''
        endDate = ''
      } else {
        startDate = this.parseTime(this.timeValue[0], '{y}-{m}-{d}')
        endDate = this.parseTime(this.timeValue[1], '{y}-{m}-{d}')
      }
      handleYLQXExport(this.ylqxList, startDate, endDate, function() {
        setTimeout(() => {
          _this.loadingFull.close()
          _this.excelLoading = false
        }, 1000)
      })
    },
    async handleYwExportList() {
      const _this = this
      this.excelLoading = true
      this.loadingFull = Loading.service({
        target: document.querySelector('.app-wrapper'),
        lock: true,
        text: '正在导出中，请稍后……',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'zIndex9999'
      })
      let startTime
      let endTime
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        startTime = ''
        endTime = ''
      } else {
        startTime = this.parseTime(this.timeValue[0])
        endTime = this.parseTime(this.timeValue[1])
      }
      const res = await workOrderList({
        page: 1,
        per_page: 99999,
        classify: 7,
        startTime,
        endTime
      })
      this.ywblfyList = res.data.data || []
      let startDate
      let endDate
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        startDate = ''
        endDate = ''
      } else {
        startDate = this.parseTime(this.timeValue[0], '{y}-{m}-{d}')
        endDate = this.parseTime(this.timeValue[1], '{y}-{m}-{d}')
      }
      handleYwExport(this.ywblfyList, startDate, endDate, function() {
        setTimeout(() => {
          _this.loadingFull.close()
          _this.excelLoading = false
        }, 1000)
      })
    },
    async handleExportList() {
      this.downloadLoading = true
      const _this = this
      const exportQuery = {}
      let ticketList = []
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        exportQuery.startTime = ''
        exportQuery.endTime = ''
      } else {
        exportQuery.startTime = this.parseTime(this.timeValue[0])
        exportQuery.endTime = this.parseTime(this.timeValue[1])
      }

      if (
        this.timeFsValue === null ||
        this.timeFsValue === undefined ||
        this.timeFsValue === ''
      ) {
        exportQuery.startFsTime = ''
        exportQuery.endFsTime = ''
      } else {
        exportQuery.startFsTime = this.parseTime(this.timeFsValue[0])
        exportQuery.endFsTime = this.parseTime(this.timeFsValue[1])
      }
      exportQuery.page = 1
      exportQuery.per_page = 99999
      exportQuery.classify = 6
      const res = await workOrderList(exportQuery)
      ticketList = res.data.data
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '事件编号',
          '事件名称',
          '事件分类',
          '事件属性',
          '发生日期',
          '上报人',
          '上报科室',
          '上报工号',
          '发生院区',
          '发生病区',
          '发生地点',
          '事件经过(详细信息)',
          '严重程度',
          '发生频率',
          'SAC评分',
          '申康上传状态',
          '流转状态',
          '上报时间'
        ]
        const filterVal = [
          'index',
          'name',
          'category',
          'sjsx_dsxz',
          'fsrq',
          'createUsers',
          'tbrqk_dept',
          'workNo',
          'hospital',
          'apply_dept',
          'fsdd',
          'sjjg',
          'yzcd',
          'fspl',
          'sjpg_sac',
          'sk_status',
          'state_name',
          'create_time'
        ]
        const listData = ticketList
        for (let i = 0; i < listData.length; i++) {
          const jsonObj = listData[i].self_data
          const jsonObjForm = listData[i].form_data
          if (jsonObj) {
            listData[i].yzcd = jsonObj['sjpg_shjg_text'] && (jsonObj['sjpg_shjg_text'] || '--')
            listData[i].fspl = jsonObj['sjpg_zfspl_text'] && (jsonObj['sjpg_zfspl_text'] || '--')
            listData[i].sjpg_sac = jsonObj['sjpg_sac'] && (jsonObj['sjpg_sac'] || '--')
          } else {
            listData[i].yzcd = '--'
            listData[i].fspl = '--'
            listData[i].sjpg_sac = '--'
          }
          if (jsonObjForm) {
            listData[i].sjjg = jsonObjForm['tbrqk_sjjg'] && (jsonObjForm['tbrqk_sjjg'] || '--')
            listData[i].fsdd = jsonObjForm['tbrqk_fsdd'] && (jsonObjForm['tbrqk_fsdd'] || '--')
            listData[i].sjsx_dsxz = jsonObjForm['sjsx_dsxz'] && (jsonObjForm['sjsx_dsxz'] || '--')
            listData[i].tbrqk_dept = jsonObjForm['tbrqk_dept'] && (jsonObjForm['tbrqk_dept'] || '--')
          } else {
            listData[i].sjjg = '--'
            listData[i].fsdd = '--'
            listData[i].sjsx_dsxz = '--'
            listData[i].tbrqk_dept = '--'
          }
          listData[i].index = i + 1
          if (listData[i].title && listData[i].title.indexOf('-') > -1) {
            listData[i].name = listData[i].title.split('-')[1]
            listData[i].category = listData[i].title.split('-')[0]
          } else {
            listData[i].name = listData[i].title
          }
          listData[i].workNo = this.userMap[listData[i].creator]

          if (listData[i].status == 0 && listData[i].is_end == 1) {
            listData[i].sk_status = '已上传'
          } else {
            listData[i].sk_status = '未上传'
          }
        }

        const data = formatJson(filterVal, listData)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '不安全事件-上报数据',
          autoWidth: true, // Optional
          bookType: 'xlsx' // Optional
        })
        this.downloadLoading = false
      })
    },
    handleExport(row) {
      this.downloadLoading = true
      const _this = this
      const jsonObj = JSON.parse(row.form_data)
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '事件名称',
          '上报人',
          '上报人工号',
          '上报时间'
        ]
        const filterVal = [
          'title',
          'user_name',
          'user_workno',
          'create_time'
        ]
        row.projectClassify = jsonObj['project_classify']
        row.leader_name = jsonObj['leader_name']
        row.user_name = jsonObj['user_name']
        row.user_workno = jsonObj['user_workno']
        row.tech_type = jsonObj['tech_type']
        row.apply_depart = jsonObj['apply_depart']

        for (let i = 0; i < _this.users.length; i++) {
          if (parseInt(jsonObj['leader_name']) == _this.users[i].userId) {
            row.leader_name = _this.users[i].nickName
          }
        }

        const data = formatJson(filterVal, [row])
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: row.title + '-上报数据',
          autoWidth: true, // Optional
          bookType: 'xlsx' // Optional
        })
        this.downloadLoading = false
      })
    },
    resetQuery() {
      this.timeValue = ''
      this.resetForm('listQuery')
      this.getList()
    },
    getInitData() {
      projectData(this.queryList).then(response => {
        this.dashboardValue = response.data
      })
    },
    formatProjectClassify(val) {
      const jsonObj = JSON.parse(val)
      return jsonObj['project_classify']
    },
    getAllList() {
      this.loading = true
      this.listQuery.page = 1
      this.listQuery.isEnd = undefined
      this.listQuery.status = undefined
      this.getList()
    },
    getCompleteList() {
      this.loading = true
      this.listQuery.page = 1
      this.listQuery.isEnd = 1
      this.listQuery.status = 0
      this.getList()
    },
    getProcessList() {
      this.loading = true
      this.listQuery.page = 1
      this.listQuery.isEnd = 0
      this.listQuery.status = 0
      this.getList()
    },
    getList() {
      this.loading = true
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      } else {
        this.listQuery.startTime = this.parseTime(this.timeValue[0])
        this.listQuery.endTime = this.parseTime(this.timeValue[1])
      }

      if (
        this.timeFsValue === null ||
        this.timeFsValue === undefined ||
        this.timeFsValue === ''
      ) {
        this.listQuery.startFsTime = ''
        this.listQuery.endFsTime = ''
      } else {
        this.listQuery.startFsTime = this.parseTime(this.timeFsValue[0])
        this.listQuery.endFsTime = this.parseTime(this.timeFsValue[1])
      }

      this.listQuery.page = this.queryParams.pageIndex
      this.listQuery.per_page = this.queryParams.pageSize
      this.listQuery.classify = 6
      workOrderList(this.listQuery).then(response => {
        this.ticketList = response.data.data
        this.queryParams.pageIndex = response.data.page
        this.queryParams.pageSize = response.data.per_page
        this.total = response.data.total_count
        this.loading = false
      })
    },

    handleView(row) {
      this.$router.push({ path: '/baqsj/review', query: { processId: row.process, workOrderId: row.id }})
    },
    handleHistoryView(row) {
      this.$refs.historyDialog.open(row.process, row.id)
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteWorkOrder(row.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getInitData()
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    initUsers() {
      listAllUser({}).then(response => {
        this.users = response.data
        for (let i = 0; i < this.users.length; i++) {
          this.userMap[this.users[i].userId] = this.users[i].workNo
        }
        this.getInitData()
        this.getList()
      })
    },
    handleInversion(row) {
      this.dialogVisible = true
      this.ruleForm.work_order_id = row.id
      this.nodeList = row.state
      if (this.nodeList.length === 1) {
        this.ruleForm.node_id = this.nodeList[0].id
      }
      listAllUser({}).then(response => {
        this.users = response.data
      })
    },
    handleSelectionChange() { },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          inversionWorkOrder(this.ruleForm).then(response => {
            if (response.code === 200) {
              this.getList()
              this.dialogVisible = false
            }
          })
        }
      })
    }
  }
}

</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 12px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .bg1 {
    background: url("~@/assets/baqsj/bg1.png") no-repeat 100%;
    background-size: cover;
  }

  .bg2 {
    background: url("~@/assets/baqsj/bg2.png") no-repeat 100%;
    background-size: cover;
  }

  .bg3 {
    background: url("~@/assets/baqsj/bg3.png") no-repeat 100%;
    background-size: cover;
  }

  .card {
    width: 357px;
    height: 128px;
    margin-right: 20px;
    margin-bottom: 10px;
    padding: 20px;
    border-radius: 10px;
    color: #000;
    position: relative;
    cursor: pointer;

    .ico-box {
      width: 50px;
      height: 50px;
      background: #fff;
      border-radius: 100%;
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        width: 30px;
        height: 32px;
      }
    }

    .number {
      color: #263238;
      font-size: 36px;
      font-weight: 500;
      margin-top: 16px;
      flex: 1;
      text-align: center;
    }

    .label {
      font-size: 20px;
      color: #111;
    }

  }
}

::v-deep .el-tabs__item {
  padding-left: 16px !important;
  height: 50px;
  line-height: 50px;
}
</style>
